package com.yy.train.ticket.utils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DemoTest2 implements Runnable{
    private static Lock locks = new ReentrantLock();
    @Override
    public void run() {
        try {
            //if(locks.tryLock()){ //尝试获取锁，获取成功则进入执行，不成功则执行finally模块
                if(locks.tryLock(6000, TimeUnit.MILLISECONDS)){ //尝试获取锁，获取成功则进入执行，不成功则执行finally模块
                System.out.println(Thread.currentThread().getName()+"-->");
                Thread.sleep(5000);
            }else{
                System.out.println(Thread.currentThread().getName()+" time out ");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            try {
                locks.unlock();
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName() + "未获取到锁，释放锁抛出异常");
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        DemoTest2 test =new DemoTest2();
        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);
        t1. start();
        t2. start();
        t1.join();
        t2.join();
        System.out.println("over");
    }
}
